import typedef


def removeComment(code: list):
    for i in range(len(code)):
        if code[i].find(';') != -1:
            code[i] = code[i].split(';')[0]


def removeIntend(code: list):
    for i in range(len(code)):
        code[i] = code[i].split('\n')[0]


def split(code: list) -> list:
    result, count = [], 0
    pMessage = None
    for i in code:
        if i.split(' ')[0] == 'SEGMENT':
            match i.split(' ')[1]:
                case 'CODE':
                    pMessage = typedef.Parament(i.split(' ')[2][:-1], 0)
                case 'DATA':
                    pMessage = typedef.Parament(i.split(' ')[2][:-1], 1)
                case 'END':
                    pMessage.size = count
                    result.append(pMessage)
            count = 0
            continue
        pMessage.datas.append(i)
        count += 1
    return result


def transform(code: typedef.Parament, arg_list: dict):
    result = []
    for i in code.datas:
        if code.type == 0:
            result.append(typedef.Command(i))
        else:
            result.append(typedef.Data(i))
    for i in result:
        i.dispatch(code.name, arg_list, result.index(i))
        i.translate(arg_list)
    code.datas = result[:]


def to_bytes(paras: list, type: str) -> bytes:
    binary = b'sandbox\x01\x03\x02'
    binary += len(paras).to_bytes(1, 'little')
    type = 0 if type.upper() == 'CODE' else 1
    binary += type.to_bytes(1, 'little')
    binary += 0x10.to_bytes(2, 'little')
    fentry = fSize = 16+(8*len(paras)//16+1)*16
    for i in paras:
        fentry = i.to_bytes(fentry)
    fSize += sum([i.size for i in paras])
    binary += fSize.to_bytes(2, 'little')
    for i in paras:
        binary += i.bytes
    if len(binary) % 16 != 0:
        for i in range(16-(len(binary) % 16), 16):
            binary += b'\xff'
    for i in paras:
        for j in i.datas:
            binary += j.binCode
        if len(binary) % 16 != 0:
            for j in range(len(binary) % 16, 16):
                binary += b'\x00'

    return binary
